package com.edu.thread.sync;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class PrintABC_03 {
    public static void main(String[] args) {

        ShareData shareData = new ShareData();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    shareData.printA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    shareData.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    shareData.printC();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

class ShareData {
    private String flag = "A"; // A B C

    ReentrantLock lock = new ReentrantLock();
    Condition a = lock.newCondition();
    Condition b = lock.newCondition();
    Condition c = lock.newCondition();

    public void printA() throws InterruptedException {
        while (true) {
            try {
                lock.lock();
                while (!flag.equals("A")) {
                    a.await();
                }
                System.out.println("A");
                flag = "B";
                Thread.sleep(1000);
                b.signal();
            } finally {
                lock.unlock();
            }
        }
    }

    public void printB() throws InterruptedException {
        while (true) {
            try {
                lock.lock();
                while (!flag.equals("B")) {
                    b.await();
                }
                System.out.println("B");
                flag = "C";
                Thread.sleep(1000);
                c.signal();
            } finally {
                lock.unlock();
            }
        }
    }


    public void printC() throws InterruptedException {
        while (true) {
            try {
                lock.lock();
                while (!flag.equals("C")) {
                    c.await();
                }
                System.out.println("C");
                flag = "A";
                Thread.sleep(1000);
                a.signal();
            } finally {
                lock.unlock();
            }
        }
    }
}
